<!--
*@Author: zt
*@Description: 人员管理
*@Date: 2024-08-14
-->
<template>
  <a-layout class="f-h-100 u-user-manager-box">
    <u-table-header>
      <u-form
        :model="searchF.model"
        :gutter="16"
        :elements="searchEl"
        class="f-w-auto"
        :isSearch="true"
        @formChange="getSearch(1)">
        <a-col>
          <u-icon-button @click="getSearch(1)">查询</u-icon-button>
        </a-col>
        <a-col flex="1">
          <a-row justify="end">
            <a-space>
              <u-icon-button itype="add" @click="toEdit(1)">新增</u-icon-button>
              <u-icon-button itype="edit" @click="toEdit(2)">编辑</u-icon-button>
              <u-icon-button @click="unlockUser">解锁</u-icon-button>
              <u-icon-button @click="setEnable(1)">启用</u-icon-button>
              <u-icon-button @click="setEnable(0)">停用</u-icon-button>
              <u-icon-button @click="resetPass">重置密码</u-icon-button>
            </a-space>
          </a-row>
        </a-col>
      </u-form>
    </u-table-header>
    <u-table-content>
      <u-table
        :columns="columns"
        :data="tabData"
        :loading="tabLoading"
        :scroll="{ y: useTableScroll() }"
        v-model:pagination="pagenation"
        @onSelect="({ selectedRows }) => (tabSelData = selectedRows)"
        @onDblclick="onDblclick"
        @change="getSearch"
      />
    </u-table-content>

    <!-- 编辑人员 -->
    <Edit
      v-model:open="showEdit"
      :title="dialogTitle"
      :fkunitsid="fkunitsid"
      :id="updateId"
      wrap-class-name="full-modal"
      @close="showEdit = false"
      @success="getSearch(), (showEdit = false)"
    />
  </a-layout>
</template>
<script lang="ts" setup>
import Edit from './Edit.vue';
import * as userService from '@/service/system/user/index';
import * as unitService from '@/service/system/unit/index';
import * as deptService from '@/service/system/dept/index';
import * as enumService from '@/service/common/enmu/index';
import * as roleService from '@/service/system/role/index';
import { formtTableEcho, formtTableEnum } from '@/util/format.ts'
import { createNamespacedHelpers } from 'vuex';
import { isValue, nullC, numberC } from '@/util/common';
import { computed, onMounted, reactive, ref, watch } from 'vue';
import { useLoginStore, useBaseStore } from '@/store';
import { storeToRefs } from 'pinia';
import { alertC } from '@/util/common';
import { useTableScroll } from '@/hooks/useTable';

const { userInfo } = storeToRefs(useLoginStore());
const { STATUS, ROLE_TYPE, POST } = storeToRefs(useBaseStore());

const unitData = ref([]);
const deptData = ref([]);
const workStatus = ref([]);
const roleData = ref([]);
const roleTypes = ref([]);
const post = ref([]);

let pagenation = reactive({
  total: 0,
  current: 1,
  pageSize: 50,
  showTotal: total => `共 ${total} 条`,
});
let searchF = reactive({
  current: 1,
  size: 20,
  sort: 'fkdeptid',
  order: 'ascending',
  model: {
    fkunitsid: null,
    fkdeptid: null,
    userstatus: null,
    roles: [],
    loginname: null,
  },
});

const formItemProps: FormItemProps = {
  labelWidth: "72px",
  colon: false,
  style: { width: '220px' }
};
const searchEl = reactive([
  { label: "所在单位", key: "fkunitsid", element: "select",
    formItemProps: formItemProps,
    hide: userInfo.value['whoAmI'] != 1,
    componentProps: {
      options: computed(() => unitData.value),
      fieldNames: {
        label: 'name',
        value: 'keyid',
        children: 'children',
      },
      props: { checkStrictly: true },
      onChange: function() {
        getDeptTree()
      }
    }
  },
  { label: "所在部门", key: "fkdeptid", element: "select",
    formItemProps: formItemProps,
    componentProps: {
      allowClear: true,
      options: computed(() => deptData.value),
      fieldNames: {
        label: 'name',
        value: 'keyid',
        children: 'children',
      },
    }
  },
  { label: "职员状态", key: "userstatus", element: "select",
    formItemProps: formItemProps,
    componentProps: {
      allowClear: true,
      options: computed(() => workStatus.value),
      fieldNames: {
        label: 'name', value: 'id'
      },
      props:{ value: 'id', label: 'name' }
    }
  },
  { label: "角色", key: "roles", element: "treeselect",
    formItemProps: { ...formItemProps, labelWidth: '54px' },
    componentProps: {
      allowClear: false,
      treeData: computed(() => roleData.value),
      fieldNames: {
        label: 'rolename', value: 'keyid' 
      },
      resultType: "Array"
    }
  },
  { label: "姓名", key: "loginname", element: "input", 
    formItemProps: { ...formItemProps, labelWidth: '54px' },
    componentProps: {
      placeholder: '姓名、登录名、昵称'
    }
  },
]);

const tabLoading = ref(false);
const total = ref(0);
const tabData = ref([]);
const tabSelData = ref([]);
let columns = ref([
  {
    title: '序号',
    width: 50,
    align: 'center',
    dataIndex: 'index',
    customRender: ({ index }) => (index += 1),
  },
  {
    title: '所在单位',
    width: 140,
    align: 'center',
    dataIndex: 'fkunitsid_echo',
    sortable: 'custom',
  },
  {
    title: '所在部门',
    width: 140,
    align: 'center',
    dataIndex: 'fkdeptid_echo',
    sortable: 'custom',
  },
  {
    title: '姓名',
    width: 120,
    align: 'center',
    dataIndex: 'username',
    sortable: 'custom',
  },
  {
    title: '登录名',
    width: 120,
    align: 'center',
    dataIndex: 'loginname',
    sortable: 'custom',
  },
  {
    title: '电话号码',
    width: 130,
    align: 'center',
    dataIndex: 'tel',
    sortable: 'custom',
  },
  {
    title: '人员状态',
    width: 100,
    align: 'center',
    dataIndex: 'userstatus_echo',
  },
  {
    title: '密码错误次数',
    width: 100,
    align: 'center',
    dataIndex: 'passworderrornum',
    customRender: ({ text }) => `${text}次`,
  },
  {
    title: '是否启用',
    width: 100,
    align: 'center',
    dataIndex: 'isenable',
    customRender: ({ text }) => (text == 1 ? '启用' : '停用'),
  },
  { title: '备注', width: 150, align: 'center', dataIndex: 'remark' },
]);

const dialogTitle = ref('新增人员');
const showEdit = ref(false);
const updateId = ref('');
const fkunitsid = ref('');

onMounted(async () => {
  if (userInfo.value['whoAmI'] != 1) {
    searchF.model.fkunitsid = userInfo.value['unitId'];
  }
  getDeptTree();

  getUnitTree();
  await getEnums();
  getSearch();
  getRolesGroudData();
});

// 获取列表数据
const getSearch = (current?: number) => {
  if (searchF.model.roles instanceof Array && searchF.model.roles.length > 0) {
    searchF.model.roles = [searchF.model.roles[searchF.model.roles.length - 1]];
  }
  if (searchF.model.userstatus) {
    searchF.model.userstatus = searchF.model.userstatus[0] || '';
  }
  let tform = JSON.parse(JSON.stringify(searchF));
  if (current == 1) {
    searchF.current = 1;
    pagenation.current = 1;
    tform.current = 1;
  }

  tform.current = pagenation.current;
  tform.size = pagenation.pageSize;

  tform.model.loginname = nullC(tform.model.loginname, null);
  tabLoading.value = true;
  userService
    .userPage(tform)
    .then(res => {
      tabLoading.value = false;
      if (res.code == 0) {
        let data = formtTableEcho(res.data.records);

        data = formtTableEnum(workStatus.value, data, 'userstatus');

        data = formtTableEnum(post.value, data, 'travelstandard');

        data.forEach(
          item => (item.edit = "<i class='iconfont icon-bianji f-cursor'></i>")
        );
        tabData.value.splice(0, tabData.value.length, ...data);

        pagenation.total = numberC(res.data.total);
      }
    })
    .catch(() => (tabLoading.value = false));
};

// 获取角色分组 的角色数据
const getRolesGroudData = async () => {
  try {
    const res = await roleService.roleGroup();
    if (res.code == 0) {
      let tdata = [];
      for (let key in res.data) {
        let index = ROLE_TYPE.value.findIndex(i => i.id == key);
        if (index != -1) {
          tdata.push({
            keyid: ROLE_TYPE.value[index]['enumName'],
            rolename: ROLE_TYPE.value[index]['name'],
            selectable: false,
            children: res.data[key],
          });
        }
      }
      roleData.value = tdata;
    }
  } catch (error) {}
};

// 获取枚举数据
const getEnums = () => {
  workStatus.value = STATUS.value;

  post.value.splice(0, post.value.length, POST.value);

  roleTypes.value.splice(0, roleTypes.value.length, ROLE_TYPE.value);
};

// 获取单位树形
const getUnitTree = () => {
  unitService
    .validTree('')
    .then(res => {
      if (res.code == 0) {
        unitData.value = res.data;
      }
    })
    .catch(() => {});
};

// 获取部门树形
const getDeptTree = () => {
  if (searchF.model.fkunitsid) {
    deptService
      .validTree(searchF.model.fkunitsid)
      .then(res => {
        if (res.code == 0) {
          deptData.value = res.data;
        }
      })
      .catch(() => {});
  } else {
    searchF.model.fkdeptid = '';
    deptData.value.splice(0, deptData.value.length);
  }
};

// type 1 新增、type 2 修改按钮
const toEdit = (type?: number | string) => {
  if (type == '1') {
    if (!isValue(searchF.model.fkunitsid)) {
      alertC('请先选择所在单位!');
      return;
    }
    updateId.value = '';
    fkunitsid.value = searchF.model.fkunitsid;
    dialogTitle.value = '人员新增';
  }
  // 修改
  else if (type == '2') {
    if (tabSelData.value.length != 1) {
      alertC('只能选择一条数据进行编辑！');
      return;
    }

    fkunitsid.value = tabSelData.value[0]['fkunitsid'];
    updateId.value = tabSelData.value[0]['keyid'];
    dialogTitle.value = '人员编辑';
  }
  showEdit.value = true;
};

// 行双击
const onDblclick = record => {
  fkunitsid.value = record['fkunitsid'];
  updateId.value = record['keyid'];
  dialogTitle.value = '人员编辑';
  showEdit.value = true;
};

// 用户解锁
const unlockUser = async () => {
  if (tabSelData.value.length == 0) {
    alertC('请先选择要解锁的数据!');
    return;
  }
  if (tabSelData.value.length > 1) {
    alertC('只能选择一条数据进行解锁!');
    return;
  }

  tabLoading.value = true;
  try {
    const res = await userService.unlock({
      userId: tabSelData.value[0]['keyid'],
    });
    if (res.code == 0) {
      alertC(res.msg, 'success');
      getSearch();
    } else {
      alertC(res.msg);
    }
  } catch (error) {}
  tabLoading.value = false;
};

// 1 启用   0 停用
const setEnable = async (isenable: number) => {
  const tip = {
    0: '停用',
    1: '启用',
  };
  if (tabSelData.value.length == 0) {
    alertC(`请先选择要${tip[isenable]}的数据!`);
    return;
  }

  let form = {
    userids: tabSelData.value.map(i => i.keyid),
    isenable,
  };
  tabLoading.value = true;
  try {
    await alertC(`确认${tip[isenable]}选中的数据?`, 'confirm');
    const res = await userService.isenable(form);
    if (res.code == 0) {
      alertC(res.msg, 'success');
      getSearch();
    } else {
      alertC(res.msg);
    }
  } catch (error) {}

  tabLoading.value = false;
};

// 重置密码
const resetPass = async () => {
  if (tabSelData.value.length == 0) {
    alertC(`请先选择要重置密码的数据!`);
    return;
  }
  if (tabSelData.value.length > 1) {
    alertC(`只能选择一条数据进行重置密码!`);
    return;
  }

  tabLoading.value = false;
  try {
    await alertC('确认重置密码?');
    const res = await userService.resetInitPW(tabSelData.value[0]['keyid']);
    if (res.code == 0) {
      alertC(res.msg, 'success');
      getSearch();
    } else {
      alertC(res.msg);
    }
  } catch (error) {}
  tabLoading.value = false;
};

// 导出
const exportBtn = () => {
  tabLoading.value = true;
  userService
    .export({ ...searchF, size: -1, filename: '人员' })
    .then(res => {
      tabLoading.value = false;
      alertC('导出成功！', 'success');
    })
    .catch(() => (tabLoading.value = false));
};

watch(
  () => searchF.model['fkunitsid'],
  () => {
    getDeptTree();
  }
);
</script>
<style lang="scss">
.u-jhk-serch-datepicker {
  .el-range-separator {
    padding: 0;
    width: unset;
  }
}

.u-user-manager-box {
  .ant-form-item {
    margin-bottom: 10px !important;
  }
}
</style>
